import { Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { CreateShowBetDto } from './dto/create-show-bet.dto';
import { PlanService } from 'src/plan/plan.service';
import { showBet } from 'generated/prisma';

@Injectable()
export class ShowBetService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly planService: PlanService,
  ) {}

  async createBets(args: Record<string, any>) {
    const { planId } = args;
    const lst = await this.findMany({ planId });
    // 如果数据库中没有，那么在数据库中添加showBets
    if (!lst.length) {
      // 1.获取方案plan中的参数
      const plan = await this.planService.findOne(+planId);
      const { ziDaoxianNum, xiangNum, calcBets } = plan!;
      // 2.计算展示区段
      const showBets = [] as showBet[];
      for (let y = 0; y < xiangNum; y++) {
        for (let x = 0; x < ziDaoxianNum; x++) {
          const lst = calcBets.map((item) => {
            return {
              calcBetId: item.id,
              ziDaoxian: x + 1,
              xiang: y + 1,
            };
          });
          showBets.push(...(lst as showBet[]));
        }
      }
      // 3.创建多个展示区段
      await this.createMany(showBets);
    }
    // 返回showBets
    return await this.findMany({ planId });
  }

  async create(createShowBetDto: CreateShowBetDto) {
    return await this.prisma.showBet.create({
      data: createShowBetDto,
    });
  }

  async createMany(createShowBetDtos: CreateShowBetDto[]) {
    return await this.prisma.showBet.createMany({
      data: createShowBetDtos,
    });
  }

  async findMany(args: Record<string, any>) {
    const { planId } = args;
    return await this.prisma.showBet.findMany({
      where: {
        calcBet: {
          planId: +planId,
        },
      },
      orderBy: { id: 'asc' },
      include: {
        calcBet: true,
      },
    });
  }
}
